package ynu.edu.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 简单监控控制器
 * 提供基本的服务发现信息
 */
@RestController
@RequestMapping("/monitor")
public class SimpleMonitorController {

    @Autowired
    private DiscoveryClient discoveryClient;

    /**
     * 获取所有注册的服务
     */
    @GetMapping("/services")
    public Map<String, Object> getServices() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<String> services = discoveryClient.getServices();
            result.put("total_services", services.size());
            result.put("services", services);
            
            // 获取provider-service的实例信息
            List<ServiceInstance> providerInstances = discoveryClient.getInstances("provider-service");
            result.put("provider_instances", providerInstances.size());
            
            Map<String, Object> instances = new HashMap<>();
            for (int i = 0; i < providerInstances.size(); i++) {
                ServiceInstance instance = providerInstances.get(i);
                Map<String, Object> info = new HashMap<>();
                info.put("host", instance.getHost());
                info.put("port", instance.getPort());
                info.put("uri", instance.getUri().toString());
                instances.put("instance_" + (i + 1), info);
            }
            result.put("provider_details", instances);
            
            System.out.println("📊 服务发现查询 - 发现 " + services.size() + " 个服务，Provider实例数: " + providerInstances.size());
            
        } catch (Exception e) {
            result.put("error", "Failed to get services: " + e.getMessage());
            System.err.println("❌ 服务发现查询失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 简单的健康检查
     */
    @GetMapping("/health")
    public Map<String, Object> health() {
        Map<String, Object> result = new HashMap<>();
        result.put("status", "UP");
        result.put("gateway", "running");
        result.put("timestamp", System.currentTimeMillis());
        return result;
    }
} 